<template>
  <section>
    <van-sticky>
      <PageHeader title="创建会员卡" />
    </van-sticky>

    <van-form @submit="onFormSubmit">
      <van-field
        v-model="card.name"
        name="name"
        label="名称"
        placeholder="请输入会员卡名称"
        required
        :rules="[{ required: true, message: '请输入会员卡名称' }]"
      />

      <van-field
        v-model="card.vip_level_label"
        readonly
        required
        label="会员等级"
        placeholder="请选择会员等级"
        is-link
        @click="vipLevelActionVisible=true">
      </van-field>

      <van-field
        v-model="card.rights_desc"
        label="权益描述"
        placeholder="请输入权益描述"
        type="textarea"
        autosize
        rows="5"
        readonly
        required
        :rules="[{ required: true, message: '权益描述不能为空' }]">
      </van-field>

      <van-field
        v-model="card.expire_days"
        type="digit"
        label="会员有效期"
        required
        placeholder="请输入会员有效期"
        :rules="[{ required: true, message: '天数不能为空' }]">
        <template #button>
          <label>天</label>
        </template>
      </van-field>

      <van-field
        v-model="card.end_active_time_str"
        readonly
        required
        label="激活截止日期"
        placeholder="请选择激活截止日期"
        is-link
        @click="endActiveTimePickerPopupVisible=true">
      </van-field>

      <van-field
        v-model="card.desc"
        label="描述"
        placeholder="请输入描述"
        type="textarea"
        autosize
        rows="5">
      </van-field>

      <van-cell-group title="正面图">
        <p class="pd10" v-if="card.frontend_image_url">
          <img :src="card.frontend_image_url" class="card-cover" />
        </p>
        <p class="pd10">
          <van-uploader name="frontend_image" :before-read="beforeUploadRead" :after-read="afterUploadRead">
            <van-button icon="plus" type="primary">上传文件</van-button>
          </van-uploader>
        </p>
      </van-cell-group>

      <van-cell-group title="背面图">
        <p class="pd10" v-if="card.backend_image_url">
          <img :src="card.backend_image_url" class="card-cover" />
        </p>
        <p class="pd10">
          <van-uploader name="backend_image" :before-read="beforeUploadRead" :after-read="afterUploadRead">
            <van-button icon="plus" type="primary">上传文件</van-button>
          </van-uploader>
        </p>
      </van-cell-group>

      <div style="margin: 16px;">
        <van-button round block type="info" native-type="submit">
          保存
        </van-button>
      </div>
    </van-form>

    <van-action-sheet v-model="vipLevelActionVisible" :actions="vipLevelActions" @select="onVipLevelSelect" cancel-text="取消" close-on-click-action />

    <van-popup v-model="endActiveTimePickerPopupVisible" round position="bottom">
      <van-datetime-picker
        v-model="currentTime"
        type="date"
        title="选择年月日"
        @confirm="onEndActivityTimeConfirm"
      />
    </van-popup>
  </section>
</template>

<script>
import PageHeader from "../../componets/PageHeader";
import {constantsUri, vipCardSaveUri, vipCardInfoUri, fileUploadByBase64Uri} from "../../../common/api";
import util from "../../../assets/js/util";

export default {
  components: {
    PageHeader
  },
  data() {
    return {
      card: {id: 0, name: '', rights_desc: '', expire_days: 30, vip_level: 0, vip_level_label: '', desc: '',
        frontend_image: 0, frontend_image_url: '', backend_image: 0, backend_image_url: '', end_active_time: 0, end_active_time_str: ''},
      vipLevels: [],
      vipLevelActions: [],
      vipLevelActionVisible: false,
      currentTime: new Date(),
      endActiveTimePickerPopupVisible: false
    }
  },
  methods: {
    beforeUploadRead(file) {
      if (file.type !== 'image/jpeg' && file.type !== 'image/png') {
        this.toast('请上传 jpg/png 格式图片');
        return false;
      }
      return true;
    },
    afterUploadRead(file, extra) {
      file.status = 'uploading';
      file.message = '上传中...';

      const that = this;
      that.$http.post(fileUploadByBase64Uri, {
        fileData: file.content,
        upload_token: that.GLOBAL.userInfo.upload_token
      }, {emulateJSON: true}).then(response => {
        let {msg, code, file_id, url} = response.body;
        if (code != 0) {
          that.toast.fail(msg);
        } else {
          if(extra.name == 'frontend_image') {
            that.card.frontend_image = file_id;
            that.card.frontend_image_url = url;
          } else if(extra.name == 'backend_image') {
            that.card.backend_image = file_id;
            that.card.backend_image_url = url;
          }
          file.status = 'done';
          file.message = '';
        }
      }, response => {
        that.toast.fail('发生错误');
      })
    },
    getConstants() {
      const that = this;
      this.$http.get(constantsUri).then(response => {
        let {code, msg, data} = response.body
        if (code != 0) {
          that.toast.fail(msg);
        } else {
          that.vipLevels = data.vip_levels;
          let vipLevelActions = [];
          for (let k = 0; k < that.vipLevels.length; k++) {
            vipLevelActions.push({
              name: that.vipLevels[k].name,
              value: that.vipLevels[k].value,
              index: k
            });
          }
          that.vipLevelActions = vipLevelActions;
        }
      }, response => {
        // error callback
      })
    },
    onVipLevelSelect(item) {
      const vipLevel = this.vipLevels[item.index];
      this.card.vip_level = vipLevel.value;
      this.card.vip_level_label = vipLevel.name;
      this.card.rights_desc = vipLevel.rights.desc;
    },
    onFormSubmit(values) {
      const that = this;
      that.$http.post(vipCardSaveUri, that.card, {emulateJSON: true}).then(response => {
        let {msg, code, data} = response.body
        if (code != 0) {
          that.toast.fail(msg);
        } else {
          that.toast.success('创建成功');
          that.$router.back();
        }
      }, response => {
        that.toast.fail('发生错误');
      })
    },
    getInfo() {
      const that = this;
      this.$http.get(vipCardInfoUri + '?id=' + this.$route.params.id).then(response => {
        let {code, msg, data} = response.body
        if (code != 0) {
          that.toast.fail(msg);
        } else {
          that.card = data.card;
          that.card.vip_level_label = data.card.vip.name;
          that.card.rights_desc = data.card.vip.rights.desc;
          that.card.end_active_time_str = util.dateFormat(that.card.end_active_time, 'yyyy-MM-dd');
        }
      }, response => {
        // error callback
      })
    },
    onEndActivityTimeConfirm(value) {
      this.card.end_active_time = value.getTime() / 1000;
      this.card.end_active_time_str = value.getFullYear() + '-' + (value.getMonth() + 1) + '-' + value.getDate();
      this.endActiveTimePickerPopupVisible = false;
    }
  },
  mounted: function () {
    this.getConstants();
    if (this.$route.name == 'MarketingEditVipCard') {
      this.card.id = this.$route.params.id;
      this.getInfo();
    }
  }
}
</script>

<style scoped>
  .card-cover {
    height: 90px;
    width: 160px;
  }
</style>
